<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Request;
use Illuminate\Foundation\Auth\ResetsPasswords;
use App\Http\Requests\UserChPass;
use Auth;
use App\Services\Interfaces\RepoServiceInterface;
use Illuminate\Support\Facades\Hash;

class PasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Create a new password controller instance.
     * 前面的中间件表示必须是没有登录才能访问PasswordController控制器.
     * @return void
     */
    public function __construct(RepoServiceInterface $_repoService)
    {
        $this->_repoService = $_repoService;
    }

    /**
     *  修改当前登录用户密码
     * @param UserChPass $request
     * @return array|\Illuminate\Database\Eloquent\Model
     */
    public function changePassword(UserChPass $request){
        $data = array();
        $data['old_pass'] = $request->input('old_pass');
        $data['password'] = $request->input('password');
        $data['password_confirmation'] = $request->input('password_confirmation');
        //if (preg_match())
        if($data['password'] == $data['old_pass']){
            return $this->_error('原密码与新密码相同');
        }
        $user = Auth::User();
        if(Hash::check($data['old_pass'], $user->password)){
            $_filter = array('id'=>$user->id);
            $data['password'] = bcrypt($data['password']);
            $isSave = $this->_repoService->update($_filter, $data);
            if($isSave){
                return "密码修改成功!";
            }else{
                return $this->_error('密码修改失败!');
            }
        }else{
            return $this->_error('原密码错误!');
        }
    }
}
